package interview.redisLock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: zhangrongqing
 * @Date: 2019/11/21 10:59
 */
//这个锁模型不可重入，即就算是同一个线程来获取也是不行的，也不能反复锁。
public class RedisLockDemo {

    public static void main(String[] args) {
        RedisLock redisLock = new RedisLock();

        String FixLockKey = "test";

        CountDownLatch countDownLatch = new CountDownLatch(10);

        final int[] count = {0};

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        long start = System.currentTimeMillis();

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executorService.execute(() -> {
                try {
                    boolean result = redisLock.lock(FixLockKey);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (result) {
                        count[0]++;
                    }
                } finally {
                    redisLock.unlock(FixLockKey);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.printf("执行线程数:%s,总耗时:%s,count数为:%s", 10, end - start, count[0]);
        executorService.shutdown();
    }
}
